//
//  SettingViewController.m
//  CKstore
//
//  Created by liliang on 13-6-18.
//  Copyright (c) 2013年 李 良. All rights reserved.
//

#import "SettingViewController.h"

@interface SettingViewController ()

@end

@implementation SettingViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(onButtonClick:)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(BOOL)shouldAutorotate{
    return YES;
}
-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}
-(id)initWithSettingDictionary:(NSDictionary*)dictionary{
    self=[self initWithStyle:UITableViewStyleGrouped];
    if (self) {
        AppController *app=[AppController shared];
        dictionary=[NSDictionary dictionaryWithDictionary:app.config];
        if (dictionary==nil) {
            dictionary=[NSDictionary dictionary];
        }
        self.dictionary=[NSMutableDictionary dictionaryWithDictionary:dictionary];
    }
    return self;
}

-(void)onButtonClick:(id)sender
{
    if (sender==self.navigationItem.leftBarButtonItem) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(NSString*)getQuestionDirectory{
    return @"information".docPath;
}

-(int)numberOfUnUploadedFiles{
    AppController *app = [AppController shared];
    NSArray *arr = [[self getQuestionDirectory] listDir];
    NSMutableArray *array = [app getAllFiles:arr];
    int num = array.count;
    if (num) {
        return num;
    }
    return 0;
}

-(void)uploadFiles
{
    int num = [self numberOfUnUploadedFiles];
    AppController *app = [AppController shared];
    NSString *store = app.config[@"store"];
    if (num != 0 && store.length != 0)
    {
        self.dictionary[@"upload"] = LOC_STR(@"正在上传");
        [self reloadTableView];

        static dispatch_queue_t uploadQueue;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            uploadQueue = dispatch_queue_create("upload", 0);
        });

        dispatch_async(uploadQueue, ^{
            NSMutableArray *files =[app getAllFiles:[@"information".docPath listDir]];
            BOOL error;
            int number = 0;
            for(NSString *filename in files)
            {
                error = [app uploadFiles:filename];
                if (!error) {
                    number += 1;
                }
            }

            if (number == 0) {
                self.dictionary[@"upload"]=LOC_STR(@"上传完成");
            }
            else
            {
                self.dictionary[@"upload"]=LOC_STR(@"上传失败");
            }
            [self reloadTableView];
        });

    }
}

-(void)updateQuestions
{
    AppController *app=[AppController shared];
    NSString *server=app.config[@"address"];
    if (server.length != 0) {
        server=[@"http://" stringByAppendingString:server];
    }
    static dispatch_queue_t downloadQueue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        downloadQueue=dispatch_queue_create("download", 0);
    });

    dispatch_async(downloadQueue, ^{
        @try {
            deviceIsBusy(YES);
            if (server.length == 0) {
                [NSException raise:LOC_STR(@"error") format:LOC_STR(@"未设置服务器"),nil];
            }else
            {
                self.dictionary[@"download"]=LOC_STR(@"正在刷新");
              
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self reloadTableView];
                });

                NSString *download=[server stringByAppendingString:@"/ministore/download.json"];
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
                [request setURL:[NSURL URLWithString:download]];
                [request setHTTPMethod:@"GET"];
                NSHTTPURLResponse *response = nil;
                NSError *error = nil;
                NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
                if (error) {
                    [NSException raise:LOC_STR(@"error") format:LOC_STR(@"服务器错误"),nil];

                }
                if (response.statusCode != 200) {
                    [NSException raise:LOC_STR(@"error") format:LOC_STR(@"服务器错误"),nil];

                }

                if ([data.jsonObject isKindOfClass:[NSArray class]]) {
                    NSMutableArray *files=[NSMutableArray array];
                    files = data.jsonObject;

                    BOOL noError=YES;
                    for (NSString *filename in files) {
                        @autoreleasepool {
                            NSString *res=[server stringByAppendingString:@"/ministore"];
                            res=[res stringByAppendingPathComponent:filename];
                            NSData *resData=[NSData dataWithContentsOfURL:[NSURL URLWithString:res]];

                            if (resData==nil) {
                                noError=NO;

                            }else{
                                NSString *localfile=filename.docPath;
                                [localfile write:resData];
                            }

                        }
                    }
                    if (noError==NO) {
                        [NSException raise:LOC_STR(@"error") format:LOC_STR(@"刷新失败"),nil];
                    }else{
                        [NSException raise:LOC_STR(@"error") format:LOC_STR(@"刷新完成"),nil];
                    }

                }
                else
                {
                    [NSException raise:LOC_STR(@"error") format:LOC_STR(@"服务器错误"),nil];

                }
            }
        }
        @catch (NSException *exception) {
            self.dictionary[@"download"]=exception.reason;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self reloadTableView];
            });
        }
        @finally {
            deviceIsBusy(NO);
        }
    });

}

-(void)selectQuestionnaire
{
    if (self.surveyArray.count) {
        UIPickerController *pick = [[UIPickerController alloc] initWithTitle:LOC_STR(@"选择问卷") andChoice:self.surveyArray];
        pick.delegate = self;
        [pick showPicker];
    }
}


-(void)pickerController:(UIPickerController*)controller didSelectedItemAtIndex:(int)index withInfo:(id)info
{
    [self.dictionary setValue:info[@"description"] forKey:@"list"];
    AppController *app = [AppController shared];
    app.config[@"id"] = info[@"id"];
    [app saveSettings];
    [self reloadTableView];
}

-(void)reloadTableView{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.dictionary[@"count"]=@([self numberOfUnUploadedFiles]).stringValue;
        self.dictionary[@"version"]=appVersion();
        [self.tableView reloadData];
    });
}

-(void)show
{
    self.settings=[NSArray arrayWithContentsOfFile:@"Setting.plist".appPath];

    [self reloadTableView];
    if (self.delegate!=nil) {
        UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:self];
        nav.modalPresentationStyle=UIModalPresentationFullScreen;
        [self.delegate presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.settings.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sec = self.settings[section];
    return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *row = self.settings[indexPath.section][indexPath.row];
    NSString *key=row[@"key"];
    NSString *name = LOC_STR(row[@"name"]);
    NSString *type = (row[@"type"]);
    NSString *CellIdentifier = type;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.clipsToBounds = YES;
        if ([type isEqualToString:@"textfield"]) {
            UITextField *textfield=[[UITextField alloc] initWithFrame:CGRectMake(0, 2, 540, 40)];
            textfield.delegate=self;
            textfield.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
            cell.accessoryView=textfield;
            textfield.autocapitalizationType = UITextAutocapitalizationTypeNone;
            textfield.autocorrectionType = UITextAutocorrectionTypeNo;
        }else{
            cell.detailTextLabel.text=nil;
        }
    }
    
    cell.userInfo = row;
    cell.textLabel.text = name;

    if ([type isEqualToString:@"textfield"]) {
        UITextField *textfield=(id)cell.accessoryView;
        textfield.userInfo=key;
        textfield.text=self.dictionary[key];
    }else{
        cell.detailTextLabel.text=nil;
        NSString *value=row[@"value"];
        if (value!=nil)
        {
            NSString *current=self.dictionary[key];
            if ([current isEqualToString:value])
            {
                cell.detailTextLabel.text=LOC_STR(@"当前");
            }
        }
        else
        {
            if (self.dictionary[key]) {
                 cell.detailTextLabel.text=self.dictionary[key];
            }
        }
    }
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    NSDictionary *row=cell.userInfo;
    NSString *type=row[@"type"];
    if ([type isEqualToString:@"button"]) {
        NSString *key=row[@"function"];
        NSString *value = row[@"value"];
        [self onClickKey:key andValue:value];
    }
    if ([type isEqualToString:@"textfield"]) {
        UITextField *textfield = (id)cell.accessoryView;
        double delayInSeconds = 0.3;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [textfield becomeFirstResponder];
        });
    }
    [self reloadTableView];
}

#pragma mark UITextFieldDelegate

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSString *key=textField.userInfo;
    NSString *value=textField.text;
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];//判断空格
    [self.dictionary setValue:value forKey:key];
    AppController *app=[AppController shared];
    app.config[key]=value;
    [app saveSettings];
    return YES;
}

-(void)onClickKey:(NSString*)key andValue:(NSString *)value
{
    SEL selector=NSSelectorFromString(key);
    [self performSelector:selector withObject:value afterDelay:0];
}

@end
